package cn.edu.scau.cmi.liangzaoqing.hibernate.dao;

import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;

import cn.edu.scau.cmi.liangzaoqing.hibernate.domain.Student;
import cn.edu.scau.cmi.liangzaoqing.util.HibernateSessionFactoryUtil;

public class StudentDAO {
	// property constants
	public static final String NAME = "name";
	public static final String NUMBER = "number";
	
private HibernateSessionFactoryUtil sessionFactoryUtil;
	
	public HibernateSessionFactoryUtil getSessionFactoryUtil() {
		return sessionFactoryUtil;
	}

	public void setSessionFactoryUtil(HibernateSessionFactoryUtil sessionFactory) {
		this.sessionFactoryUtil = sessionFactory;
	}
	
	public void save(Student transientInstance) {
		try {
			sessionFactoryUtil.getSession().save(transientInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void delete(Student persistentInstance) {
		try {
			sessionFactoryUtil.getSession().delete(persistentInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public Student findById(java.lang.Long id) {
		try {
			Student instance = (Student) sessionFactoryUtil.getSession().get("cn.edu.scau.cmi.liangzaoqing.hibernate.Student", id);
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findByExample(Student instance) {
		try {
			List results = sessionFactoryUtil.getSession().createCriteria("cn.edu.scau.cmi.liangzaoqing.hibernate.Student")
					.add(Example.create(instance)).list();
			return results;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		try {
			String queryString = "from Student as model where model." + propertyName + "= ?";
			Query queryObject = sessionFactoryUtil.getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}

	public List findByNumber(Object number) {
		return findByProperty(NUMBER, number);
	}

	public List findAll() {
		try {
			String queryString = "from Student";
			Query queryObject = sessionFactoryUtil.getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public Student merge(Student detachedInstance) {
		try {
			Student result = (Student) sessionFactoryUtil.getSession().merge(detachedInstance);
			return result;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void attachDirty(Student instance) {
		try {
			sessionFactoryUtil.getSession().saveOrUpdate(instance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void attachClean(Student instance) {
		try {
			sessionFactoryUtil.getSession().buildLockRequest(LockOptions.NONE).lock(instance);
		} catch (RuntimeException re) {
			throw re;
		}
	}
}